<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */
namespace app\api\model\dao;

use think\Model;
use think\Db;

class CircleStatistics extends Model
{
    protected $table = 'circle_statistics';

    protected $pk = 'id';

    /**
     * 添加统计记录
     *
     */
    public function addCircleStatistics($arrInput)
    {
        $sql = sprintf("insert into %s(cir_id, userid, pv, create_time) values(%d,%d,%d,%d) on duplicate key update pv=pv+1", $this->table, $arrInput['cir_id'], $arrInput['userid'], 1, time());
        return Db::table($this->table)->query($sql);
    }

    /**
     * 根据帖子id和用户id获取统计记录
     *
     */
    public function getCircleStatisticsOne($cir_id, $userid)
    {
        $arrCond = [
            'cir_id' => ['=', $cir_id],
            'userid' => ['=', $userid],
        ];

        return Db::table($this->table)->where($arrCond)->select();
    }

    /**
     * 获取帖子列表
     *
     * @param array $conds
     * @param array $fields
     * @param int $offset
     * @param int $limit
     * @param string $orderby
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCircleStatistics($conds = [], $fields = [], $offset = 0, $limit = 10000, $orderby = '', $groupby = '')
    {
        $this->allowField(true);

        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';

        $arrField = [];
        foreach ($fields as $val) {
            if (in_array($val, $this->field)) {
                $arrField[] = $val;
            }
        }
        empty($arrField) && $arrField = $this->field;

        return Db::table($this->table)->where($arrCond)->limit($offset, $limit)->order($orderby)->field($arrField)->select();
    }

    /**
     * 获取圈子PV
     *
     */
    public function getCirclePvTop($strConds = '1=1', $top_num = 5)
    {
        $sql = sprintf("select cir_id,sum(pv) as pv_sum from %s where %s group by cir_id order by pv_sum desc limit 0,%d", $this->table, $strConds, $top_num);
        return Db::table($this->table)->query($sql);
    }

}
